package com.cloudm.technician.extensions

import com.cloudm.technician.data.model.VersionInfo

/**
 * 作者: wesley
 * 时间: 2017/12/26
 * 描述:
 */


fun VersionInfo.compareVersion(version1: String): Int {
    val version2 = this.version ?: return 0
    if (version1 == version2) {
        return 0
    }
    val version1Array = version1.split(
            "\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    val version2Array = version2.split(
            "\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    var index = 0
    val minLen = Math.min(version1Array.size, version2Array.size)
    var diff = 0
    try {
        while (index < minLen) {
            diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])
            if (diff == 0) {
                index++
            } else {
                break
            }
        }
        return if (diff == 0) {
            (index until version1Array.size).filter {
                Integer.parseInt(version1Array[it]) > 0
            }.forEach { return 1 }
            if ((index until version2Array.size).any {
                Integer.parseInt(version2Array[it]) > 0
            }) -1 else 0
        } else {
            if (diff > 0) 1 else -1
        }
    } catch (e: Exception) {
        logger(e.toString())
    }
    return 0
}